import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {
  Button,
  Modal,
  Table,
  Tooltip,
  Select,
  Form,
  Row,
  Col,
  Input,
  DatePicker,
} from 'antd';
import moment from 'moment';
import xlsx from 'xlsx';
import util from '@/compontents/util.js';
const { confirm } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;

const { uOrderCheck, uSchoolManageList, uOrderCheckUptate } = api;
export default (props: any) => {
  const { manageId, schoolId, userName } = JSON.parse(
    sessionStorage.info,
  ).userInfo;
  const columns: any = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 100,
      render: (text: any, record: any, index: any) => `${index + 1}`,
    },
    {
      title: '订单号',
      dataIndex: 'orderNum',
      width: 160,
    },
    {
      title: '订单总价',
      dataIndex: 'price',
      ellipsis: {
        showTitle: false,
      },
    },
    {
      title: '券数量',
      dataIndex: 'ticketNum',
    },
    {
      title: '核算状态',
      dataIndex: 'isCheck',
      render: (v1: any, v2: any) => <div>{formatStatus(v2.isCheck)}</div>,
    },
    {
      title: '商铺',
      dataIndex: 'uBusinessId',
      ellipsis: {
        showTitle: false,
      },
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={formatSchool(v2.businessManageId)}>
          {formatSchool(v2.businessManageId)}
        </Tooltip>
      ),
    },
    {
      title: '订单备注',
      dataIndex: 'remark',
    },
    {
      title: '下单时间',
      dataIndex: 'time',
      ellipsis: {
        showTitle: false,
      },
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={util.formatTime(v2.time)}>
          {util.formatTime(v2.time)}
        </Tooltip>
      ),
    },
    {
      title: '订单结束时间',
      dataIndex: 'endTime',
      ellipsis: {
        showTitle: false,
      },
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={util.formatTime(v2.endTime)}>
          {util.formatTime(v2.endTime)}
        </Tooltip>
      ),
    },
  ];
  const [list, setList]: any = useState([]);
  const [total, setTotal] = useState(0);

  // 核算总金额
  const [priceAll, setPriceAll] = useState(0);
  // 核算订单ID数组
  const [checkArr, setCheckArr] = useState([]);

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 学校列表
  const [schoolList, setSchoolList]: any = useState([]);

  // 订单状态列表
  const statusList = [
    {
      id: 1,
      name: '未核算',
    },
    {
      id: 2,
      name: '已核算',
    },
  ];
  // 商家列表
  const [businessManageId, setBusinessManageId] = useState(0);
  // 获取入驻学校列表
  const getSchoolList = () => {
    uSchoolManageList({
      pageNo: 1,
      pageSize: 100000,
      schoolId,
      type: 2,
    }).then((res: any) => {
      const { list, total } = res.data;
      setSchoolList(list);
    });
  };
  const formItemLayout = {
    labelCol: {
      xxl: {
        span: 6,
      },
      xl: {
        span: 8,
      },
    },
    wrapperCol: {
      xxl: {
        span: 18,
      },
      xl: {
        span: 16,
      },
    },
  };
  const [filData, setFilData] = useState({
    pageNo: 1,
    pageSize: 10,
    isCheck: 0,
    businessManageId: 0,
    orderNum: '',
    startDate: '',
    endDate: '',
    uSchoolId: schoolId,
  });
  const getList = (data: any) => {
    uOrderCheck(data).then((res: any) => {
      const { list, total } = res.data;
      setList(list);
      setTotal(total);
    });
  };
  // 分页改变
  const pageChange = (pageNo2: any, pageSize2: any) => {
    const params = { ...filData };
    params.pageNo = pageNo2;
    params.pageSize = pageSize2;
    setFilData(params);
    getList(params);
  };

  const formatStatus = (id: any) => {
    if (statusList.length) {
      const name = statusList.filter((item: any) => item.id === id)[0].name;
      return name;
    }
  };
  const formatSchool = (id: any) => {
    let name = '';
    if (schoolList.filter((item: any) => item.manageId === id).length) {
      name = schoolList.filter((item: any) => item.manageId === id)[0].name;
    }
    return name;
  };

  // 学校下拉列表改变
  const filChange1 = (e: any) => {
    const params = { ...filData };
    if (e) {
      params.businessManageId = e;
    } else {
      params.businessManageId = 0;
    }

    setFilData(params);
    getList(params);
  };
  // 下拉列表改变
  const filChange2 = (e: any) => {
    const params = { ...filData };
    params.isCheck = e ? e : 0;
    setFilData(params);
    getList(params);
  };
  const filChange3 = (e: any) => {
    const params = { ...filData };
    params.orderNum = e.target.value;
    setFilData(params);
    getList(params);
  };

  const filChange4 = (e: any) => {
    const params = { ...filData };
    params.startDate = e ? moment(e[0]).format('YYYY-MM-DD HH:mm:ss') : '';
    params.endDate = e ? moment(e[1]).format('YYYY-MM-DD HH:mm:ss') : '';
    setFilData(params);
    getList(params);
  };

  const toExcel = () => {
    const jsono = util.xlsx.getGridDataToJson('#excel');
    util.xlsx.downloadExl(jsono, xlsx, 'order');
  };

  // 多选
  const selectChange = (e: any) => {
    setSelectedRowKeys(e);
    let [arr, num]: any = [[], 0];
    e.map((item: any) => {
      arr.push(list[item].id);
      num += parseFloat(list[item].price);
    });
    setCheckArr(arr);
    setPriceAll(num);
  };

  // 点击订单核算按钮
  const orderCheck = () => {
    if (priceAll > 0) {
      Modal.confirm({
        title: '提示',
        content: `核算金额为￥${priceAll}，该操作不可逆，请仔细检查金额后操作！`,
        onOk() {
          uOrderCheckUptate({ ids: checkArr }).then(res => {
            getList(filData);
            setSelectedRowKeys([]);
          });
        },
      });
    } else {
      Modal.error({
        title: '提示',
        content: '请至少选择一个订单进行核算！',
      });
    }
  };

  useEffect(() => {
    getList(filData);
    getSchoolList();
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <div className={styles.tool}>
          <Form hideRequiredMark={true}>
            <Row gutter={24} justify="start">
              <Col span={8}>
                <Form.Item label="选择商铺" {...formItemLayout}>
                  <Select
                    showSearch
                    placeholder="请选择商铺"
                    allowClear
                    onChange={filChange1}
                  >
                    {schoolList.map((item: any, i: any) => (
                      <Option key={item.manageId} value={item.manageId}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="核算状态" {...formItemLayout}>
                  <Select
                    showSearch
                    placeholder="请选择核算状态"
                    allowClear
                    onChange={filChange2}
                  >
                    {statusList.map((item: any, i: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="订单号" {...formItemLayout}>
                  <Input onChange={filChange3} placeholder="请输入订单号" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Form hideRequiredMark={true}>
            <Row gutter={24} justify="start">
              <Col span={8}>
                <Form.Item label="选择日期" {...formItemLayout}>
                  <RangePicker
                    onChange={filChange4}
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item colon={false} label=" " {...formItemLayout}>
                  <Button
                    onClick={() => {
                      toExcel();
                    }}
                    type="primary"
                  >
                    导出订单excel
                  </Button>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item colon={false} label=" " {...formItemLayout}>
                  <span className={styles.priceAll}>
                    核算总金额：￥{priceAll}
                  </span>
                  <Button
                    onClick={() => {
                      orderCheck();
                    }}
                    type="primary"
                  >
                    订单核算
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>

        {schoolList.length ? (
          <Table
            id="excel"
            dataSource={list}
            columns={columns}
            rowSelection={{
              selectedRowKeys,
              type: 'checkbox',
              // ...rowSelection,
              onChange: selectChange,
              getCheckboxProps: record => ({
                disabled: record.isCheck === 2,
                isCheck: record.isCheck,
              }),
            }}
            pagination={{
              showQuickJumper: true,
              total,
              defaultCurrent: filData.pageNo,
              defaultPageSize: filData.pageSize,
              size: 'small',
              onChange: pageChange,
              showTotal: () => {
                return `总共 ${total} 条记录`;
              },
            }}
          />
        ) : (
          <div></div>
        )}
      </div>
    </CardCommon>
  );
};
